<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\facade\Db;

class DataProject extends AdminBase
{
    public function index()
    {
        $param = $this->request->param();
        $db = Db::name('data_project'); 
        if(!empty($param['parent_typeid'])) {
            $db = $db->where('parent_typeid',$param['parent_typeid']);
            if(!empty($param['typeid'])){
                $db = $db->where('typeid',$param['typeid']);
            }
        }
        if(!empty($param['tort'])){
            $db = $db->where('tort',$param['tort']);
        }
        if(!empty($param['kw'])){
            $db = $db->where($param['field'],'like','%'.$param['kw'].'%');
        }
        $list = $db->order('id desc')->paginate(['list_rows'=> 100,'query' => $param]);
        $count = $list->total();
        $parent_typelist = Db::name('data_type')->where('level',1)->select()->toArray();
        $typelist = Db::name('data_type')->where([
            'level' => 2,
            'pid' => $param['parent_typeid']
        ])->select()->toArray();
        $repeat = Db::name('data_project_repeat')->select()->toArray();
        return view('',['list'=>$list,'count'=>$count,'param'=>$param,'parent_typelist'=>$parent_typelist,'typelist'=>$typelist,'repeat'=>$repeat]);
    }

    public function add()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            if(!empty($param['parent_typeid'])) $param['top_typeid'] = get_typepid($param['parent_typeid']);
            $result = Db::name('data_project')->insert($param);
            if( $result ) {
                xn_add_admin_log('添加项目');
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        $parent_typelist = Db::name('data_type')->where('level',1)->select()->toArray();
        return view('form',['parent_typelist'=>$parent_typelist]);
    }

    public function edit()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            if(!empty($param['parent_typeid'])) $param['top_typeid'] = get_typepid($param['parent_typeid']);
            $result = Db::name('data_project')->update($param);
            if( $result ) {
                xn_add_admin_log('修改项目');
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }

        $id = $this->request->get('id');
        $data = Db::name('data_project')->where('id',$id)->find();
        $parent_typelist = Db::name('data_type')->where('level',1)->select()->toArray();
        $typelist = Db::name('data_type')->where([
            'level' => 2,
            'pid' => $data['parent_typeid']
        ])->select()->toArray();
        $contentlist = Db::name('data_project_content')->field('id,content')->where('project',$data['title'])->select();
        return view('form',['data'=>$data,'parent_typelist'=>$parent_typelist,'typelist'=>$typelist,'contentlist'=>$contentlist]);
    }

    public function delete()
    {
        $id = intval($this->request->get('id'));
        !($id>0) && $this->error('参数错误');
        Db::name('data_project')->delete($id);
        xn_add_admin_log('删除项目');
        $this->success('删除成功');
    }

    public function deleteAll(){
        $ids = $this->request->get('ids');
        ($ids=='') && $this->error('参数错误');
        $ids = explode(',',$ids);
        Db::name('data_project')->delete($ids);
        xn_add_admin_log('批量删除项目');
        $this->success("删除成功");
    }

    public function import(){
        $file = request()->file('file');
        $savename = \think\facade\Filesystem::putFileAs( 'excel', $file, 'project.xlsx');
        if(!$savename){
            return json(['status'=>'0','msg'=>'文件上传失败!']);
        }
        $filePath = \think\facade\Filesystem::path($savename);

        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)) {
                return json(['status'=>'0','msg'=>'No Excel!']);
            }
        }

        $PHPExcel = $PHPReader->load($filePath);
        $currentSheet = $PHPExcel->getSheet(0);
        //$allColumn = $currentSheet->getHighestColumn();
        $allRow = $currentSheet->getHighestRow();

        $limitNum = 10;
        $limitPage = ceil($allRow / $limitNum);
        $count = 0;
        for($i=0;$i<$limitPage;$i++){
            $limitIndex = $i * $limitNum;
            $limitEnd = $limitIndex + $limitNum;
            if($i == 0){
                $limitIndex = 2;
            }
            if($limitEnd >= $allRow){
                $limitEnd = $allRow+1;
            }
            for($currentRow = $limitIndex; $currentRow < $limitEnd; $currentRow++) {
                $dalei = $currentSheet->getCell('A'.$currentRow)->getValue();
                $xiaolei = $currentSheet->getCell('B'.$currentRow)->getValue();
                $data['title'] = $currentSheet->getCell('C'.$currentRow)->getValue();
                $data['alias'] = $currentSheet->getCell('D'.$currentRow)->getValue();
                $data['company'] = $currentSheet->getCell('E'.$currentRow)->getValue();
                $data['slogan'] = $currentSheet->getCell('F'.$currentRow)->getValue();
                $data['cost_min'] = $currentSheet->getCell('G'.$currentRow)->getValue();
                $data['cost_max'] = $currentSheet->getCell('H'.$currentRow)->getValue();
                if(empty($data['title'])) continue;
                if(empty($data['company'])) $data['company'] = '';
                if(empty($data['slogan'])) $data['slogan'] = '';
                if(empty($data['cost_min'])) $data['cost_min'] = '';
                if(empty($data['cost_max'])) $data['cost_max'] = '';
                
                $type1 = Db::name('data_type')->field('id,alias')->where([
                    'level' => 1,
                    'title' => $dalei
                ])->find();
                if($type1) {
                    $data['parent_typeid'] = $type1['id'];
                    $data['top_typeid'] = get_typepid($data['parent_typeid']);
                }
                $type2 = Db::name('data_type')->field('id,alias')->where([
                    'level' => 2,
                    'title' => $xiaolei
                ])->find();
                if($type2) $data['typeid'] = $type2['id'];
                // if($data['alias'] == '' && $type2['alias']){
                //     $arr = explode(',',$type2['alias']);
                //     foreach($arr as $v){
                //         if(strpos($data['title'],$v) !== false){
                //             $str = str_replace($v,'',$data['title']);
                //             $len = mb_strlen($str,'UTF8'); 
                //             if($len > 2){
                //                 $data['alias'] = $str;
                //             }
                //             break;
                //         }
                //     }
                //     if($data['alias'] == ''){
                //         $data['alias'] = $data['title'];
                //     }
                // }
                if(empty($data['alias'])){
                    $data['alias'] = $data['title'];
                }
                $r = Db::name('data_project')->where([
                    'typeid' => $data['typeid'],
                    'title' => $data['title']
                ])->find();
                if(!$r){
                    $insertId = Db::name('data_project')->insertGetId($data);
                    if($insertId){
                        if(!empty($data['company'])){
                            $com = DB::name('data_company')->where('title',$data['company'])->find();
                            if(empty($com)){
                                $com = apiGetCom($data['company']);
                                $com = json_decode($com,true);
                                if(!empty($com['result'])){
                                    $com = $com['result'];
                                    $com['title'] = $data['company']; 
                                    Db::name('data_company')->insert($com);
                                }
                            }
                        }
                        $count++;
                        // $arr = explode(',',$data['alias']);
                        // foreach($arr as $v){
                        //     $res = Db::name('data_project')->field('id')->whereRaw("id != $insertId AND typeid = {$data['typeid']} AND FIND_IN_SET('$v',alias)")->find();
                        //     if($res){
                        //         Db::name('data_project_repeat')->insert(['proid' => $insertId, 'repid' => $res['id']]);
                        //         break;
                        //     }
                        // }
                    }
                }
            }
        }
        return json(['status'=>'1','msg'=>'成功导入 '.$count.' 条数据']);
    }

    public function getProjectByLike(){
        $param = $this->request->param();
        $data = Db::name('data_project')->field('id,title,typeid,parent_typeid')->where('title','like',$param['word'].'%')->select()->toArray();
        if(empty($data)){
            return json(['status'=>0,'msg'=>'没有数据']);
        }
        return json(['status'=>1,'msg'=>'执行成功','data'=>$data]);
    }

    public function getProjectByName(){
        $param = $this->request->param();
        $data = Db::name('data_project')->field('id,title')->where('title',$param['word'])->find();
        if(empty($data)){
            return json(['status'=>0,'msg'=>'没有数据']);
        }
        return json(['status'=>1,'msg'=>'执行成功','data'=>$data]);
    }

    public function delRepeat(){
        $id = intval($this->request->get('id'));
        !($id>0) && $this->error('参数错误');
        Db::name('data_project_repeat')->delete($id);
        $this->success('移除成功');
    }

    public function matchingCompany(){
        $start = intval($this->request->get('start'));
        $end = intval($this->request->get('end'));
        $flag = intval($this->request->get('flag'));
        $map = [];
        $map2 = [];
        if($flag == 0){
            $map[] = ['company_exist','=',0];
            $map2[] = ['company_exist','=',0];
        }
        if(empty($start) || empty($end)){
            $start = Db::name('data_project')->where($map)->field('id')->order('id asc')->find();
            $end = Db::name('data_project')->where($map)->field('id')->order('id desc')->find();
            if(!empty($start) && !empty($end)){
                $start = $start['id'];
                $end = $end['id'];
            }else{
                return json([
                    'status' => 0,
                    'msg' => '没有可匹配的数据'
                ]);
            }
        }
        if($start > $end){
            return json([
                'status' => 0,
                'msg' => '执行完毕'
            ]);
        }
        $limit = 1000;
        $nextStart = ($start+$limit);
        $map[] = ['id','>=',$start];
        $map[] = ['id','<',$nextStart];
        $list = Db::name('data_project')->where($map)->field('id,company')->order('id asc')->select()->toArray();
        if(!empty($list)){
            foreach($list as $v){
                $r = Db::name('data_company')->where('title',$v['company'])->find();
                if($r){;
                    Db::name('data_project')->where('id',$v['id'])->update(['company_exist'=>1]);
                }else{
                    if(!empty($flag)){
                        Db::name('data_project')->where('id',$v['id'])->update(['company_exist'=>0]);
                    }
                }
            }
        }
        $map2[] = ['id','>=',$nextStart];
        $_nextStart = Db::name('data_project')->where($map2)->field('id')->order('id asc')->find();
        if(!empty($_nextStart)){
            $_start = $_nextStart['id'];
        }else{
            return json([
                'status' => 0,
                'msg' => '全部执行完毕'
            ]);
        }
        // echo '<script>window.location.href="http://www.xnadmin.site/admin/DataProject/matchingCompany/?start='.$_start.'&end='.$end.'";</script>';
        return json([
            'status' => 1,
            'msg' => '正在执行，ID:'.$start.'至'.$nextStart.'，结束ID:'.$end,
            'data' => ['start' => $_start, 'end' => $end]
        ]);
    }

    public function getShopNum(){
        $start = intval($this->request->get('start'));
        $end = intval($this->request->get('end'));
        $flag = intval($this->request->get('flag'));
        $map[] = ['shop_get','=',1];
        $map2[] = ['shop_get','=',1];
        if($flag == 0){
            $map[] = ['shop_num','=',0];
            $map2[] = ['shop_num','=',0];
        }
        if(empty($start) || empty($end)){
            $start = Db::name('data_project')->where($map)->field('id')->order('id asc')->find();
            $end = Db::name('data_project')->where($map)->field('id')->order('id desc')->find();
            if(!empty($start) && !empty($end)){
                $start = $start['id'];
                $end = $end['id'];
            }else{
                return json([
                    'status' => 0,
                    'msg' => '没有可匹配的数据'
                ]);
            }
        }
        if($start > $end){
            return json([
                'status' => 0,
                'msg' => '执行完毕'
            ]);
        }
        $limit = 10;
        $nextStart = ($start+$limit);
        $map[] = ['id','>=',$start];
        $map[] = ['id','<',$nextStart];
        $list = Db::name('data_project')->where($map)->field('id,title,typeid')->order('id asc')->select()->toArray();
        if(!empty($list)){
            foreach($list as $v){
                $count = Db::name('data_project_shop')->where([
                    'typeid' => $v['typeid'],
                    'project' => $v['title']
                ])->count();
                Db::name('data_project')->where('id',$v['id'])->update(['shop_num' => $count]);
            }
        }
        $map2[] = ['id','>=',$nextStart];
        $_nextStart = Db::name('data_project')->where($map2)->field('id')->order('id asc')->find();
        if(!empty($_nextStart)){
            $_start = $_nextStart['id'];
        }else{
            return json([
                'status' => 0,
                'msg' => '全部执行完毕'
            ]);
        }
        // echo '<script>window.location.href="http://www.xnadmin.site/admin/DataProject/matchingCompany/?start='.$_start.'&end='.$end.'";</script>';
        return json([
            'status' => 1,
            'msg' => '正在执行，ID:'.$start.'至'.$nextStart.'，结束ID:'.$end,
            'data' => ['start' => $_start, 'end' => $end]
        ]);
    }

}
